﻿using Growatt.OSC.Util;
using Growatt.WaveData.DataSetResolve;
using LEDVANCE.Oscilloscope.VirtualOscilloscope.DataGridViewHelper;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Vosc;
using Vosc.VirtualOscilloscope;

namespace Growatt.WaveData.VirtualOscilloscope
{

    /// <summary>
    /// 参数配置界面
    /// </summary>
    public partial class UC_ParameterSetting : UserControl
    {

        public enum Typemodel
        {
            U16,
            I16,
            F32,
        }
        public enum Scalemodel
        {
            x10,
            x100,
            x1k,
            x10k,
            x100k,
        }
        public string Address { get; set; }
        public int I { get; }


        private UIComboDataGridView uiComboDataGridView2 = new UIComboDataGridView()
        {
            DropDownWidth = 500,
            Font = new System.Drawing.Font("宋体", 8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)))
        };

        public void ChangetextBox1(string text)
        {
            try
            {
                if (!string.IsNullOrEmpty(uiComboDataGridView2.Text))
                {
                    VariableInfo variableInfo = new VariableInfo(uiComboDataGridView2.Text, string.Empty);
                    DwarfHelper.DwarfHelperInstance.GetAddress(new List<VariableInfo>() { variableInfo });

                    if (!string.IsNullOrEmpty(variableInfo.Address))
                    {
                        textBox_address.Text = variableInfo.Address;
                    }
                    else
                    {
                        textBox_address.Text = "0000000";
                    }
                }
                else
                {
                    textBox_address.Text = "0000000";
                }
            }
            catch (Exception)
            {

            }
        }

        DatagirdViewHelper datagirdViewHelper = null;
        DataTable dt = new DataTable();

        UIDataGridView uIDataGridView = null;

        public Action<string> ShowParameter = null;
        public UC_ParameterSetting(int i,ModelSaveString modelSaveString)
        {
            cuurentSelectItem = modelSaveString;
            InitializeComponent();
            this.Load += (_, u) =>
            {
                this.components = new System.ComponentModel.Container();
                UIStyleManager StyleManager = new Sunny.UI.UIStyleManager(this.components);
                UIStyle style = (UIStyle)101;
                if (style != UIStyle.Colorful)
                    StyleManager.Style = style;
            };
            uiComboDataGridView2.DataGridView.Init();
            uiComboDataGridView2.DataGridView.MultiSelect = true;//设置可多选
            uiComboDataGridView2.ItemSize = new System.Drawing.Size(500, 200);
            uiComboDataGridView2.DataGridView.AddColumn("参数名称", "Name");
            uiComboDataGridView2.DataGridView.AddColumn("类型", "Type", fillWeight: 20);
            uiComboDataGridView2.DataGridView.AddColumn("倍率", "Scale", fillWeight: 20);
            uiComboDataGridView2.DataGridView.AddColumn("地址", "Address", fillWeight: 30);
            //uiComboDataGridView2.DataGridView.AddColumn("偏移", "SignalOffset", fillWeight: 20);
            uiComboDataGridView2.DataGridView.ReadOnly = false;
            uiComboDataGridView2.ShowFilter = false;
            datagirdViewHelper = new DatagirdViewHelper(uiComboDataGridView2.DataGridView);
            HideControlsWithTextHelper.HideControlsWithText(uiComboDataGridView2.item, "删除");
            HideControlsWithTextHelper.HideControlsWithText(uiComboDataGridView2.item, "搜索");

            uiComboDataGridView2.FilterChanged += UiComboDataGridView2_FilterChanged;
            //点击删除按钮
            uiComboDataGridView2.item.DelItems += () =>
            {
                var del = DatagirdViewHelper.modelList.Where(o => o.IsSelected).ToList();
                for (global::System.Int32 j = 0; j < del.Count; j++)
                {
                    var delModel = del[j];
                    datagirdViewHelper.DeleteModel(delModel);
                }
            };
            uiComboDataGridView2.BackColor = Color.Red;
            uiComboDataGridView2.ForeColor = Color.Gray;
            var font = new System.Drawing.Font("微软雅黑", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            uiComboDataGridView2.Font = font;
            uIDataGridView = uiComboDataGridView2.DataGridView;
            UC_BtnAddDelControl userControl3 = new UC_BtnAddDelControl(this, uiComboDataGridView2, DatagirdViewHelper.modelList,null, (data) =>
            {
                if (cuurentSelectItem != null)
                {
                    var delModel = DatagirdViewHelper.modelList.Where(o => o.Name.Equals(cuurentSelectItem.Name)).FirstOrDefault();
                    if (delModel != null)
                    {
                        datagirdViewHelper.AddModel(delModel);
                        uiComboDataGridView2.Text = ""; //清空文本
                    }
                }
            })
            { Dock = DockStyle.Top };
            userControl3.AddAction += ((string name, string type, string scale, string add,string offset) k) =>
            {


                uiComboDataGridView2.Text = k.name;
                textBoxType.Text = k.type;
                textBoxScale.Text = k.scale;
                textBox_address.Text = k.add;
                //textBox_offset.Text = k.offset; //offset
                var delModel = DatagirdViewHelper.modelList.FirstOrDefault(o => o.Name.Equals(uiComboDataGridView2.Text)
                );
                if (delModel != null)
                {
                    cuurentSelectItem = delModel;
                }
                else
                {

                }
                ShowParameter?.Invoke("通道" + i + ":   " + uiComboDataGridView2.Text);
            };

            // 绑定属性到 TextBox
    
 



            uiComboDataGridView2.FilterColumnName = "参数名称"; //不设置则全部列过滤
            panel3.Controls.Add(uiComboDataGridView2);
            uiComboDataGridView2.Dock = DockStyle.Top;
            userControl3.Anchor = AnchorStyles.Left;
            panel2.Controls.Add(userControl3);
            textBoxType.SelectedIndex = 0;
            textBoxScale.SelectedIndex = 0;
            textBoxType.Name = $"comboBoxCH_{i}Type";
            textBoxScale.Name = $"comboBoxCH_{i}ratio";
            uiComboDataGridView2.Name = $"textBoxCH{i}Name";
            textBox_address.Name = $"textBoxCH{i}Address";
            textBox_offset.Name = $"textBoxCH{i}Offset";

            I = i;
            this.uiComboDataGridView2.ValueChanged += new Sunny.UI.UIComboDataGridView.OnValueChanged(this.uiComboDataGridView2_ValueChanged);
            this.uiComboDataGridView2.DataGridView.DataError += DataGridView_DataError;
        }
        

        public static List<ModelSaveString> originalDataSource = new List<ModelSaveString>();

        private List<ModelSaveString> filteredDataSource = new List<ModelSaveString>();

     
        private void UiComboDataGridView2_FilterChanged(object sender, UIComboDataGridViewArgs e)
        {
            datagirdViewHelper.SearchModels(e.FilterText);

        }
     
        private void DataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
        }



        //当前选中的
        public ModelSaveString cuurentSelectItem = new ModelSaveString();



        private void dgv_SequenceRunState_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            //遍历选中颜色事件
            if (e.RowIndex == -1)
                return;

            Color colorToChange = Color.LightBlue;
            Color colorCurrent = uIDataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor;

            if (colorCurrent == Color.LightGreen)
                colorToChange = Color.PaleGreen;
            for (int i = 1; i < 7; i++)
            {
                if (i == 3 || i == 4)
                {
                    continue;
                }
                uIDataGridView.Rows[e.RowIndex].Cells[i].Style.BackColor = colorToChange;
            }
        }


        private void uiComboDataGridView2_ValueChanged(object sender, object value)
        {
            try
            {
                uiComboDataGridView2.Text = "";
                // 假设你使用 BindingSource 绑定数据
                if (DatagirdViewHelper.modelList != null && DatagirdViewHelper.modelList.Count > 0)
                {

                    if (value != null && value is DataGridViewSelectedRowCollection)
                    {
                        DataGridViewSelectedRowCollection collection = uiComboDataGridView2.DataGridView.SelectedRows;
                        foreach (var item in collection)
                        {

                            Debug.WriteLine(item.ToString());
                            DataGridViewRow row = (DataGridViewRow)item;
                            ModelSaveString selectParaInfo = row.DataBoundItem as ModelSaveString;
                            if (selectParaInfo != null)
                            {
                                cuurentSelectItem = DatagirdViewHelper.modelList.FirstOrDefault(o => o.Name.Equals(selectParaInfo.Name));
                                uiComboDataGridView2.Text += row.Cells["参数名称"].Value.ToString();
                                textBoxType.Text = selectParaInfo.Type;
                                textBoxScale.Text = selectParaInfo.Scale;
                                textBox_address.Text = selectParaInfo.Address;
                                uiComboDataGridView2.Text = selectParaInfo.Name;
                                //textBox_offset.Text = selectParaInfo.SignalOffset;
                                ShowParameter?.Invoke("通道" + I + ":  " + uiComboDataGridView2.Text);
                            }

                        }
                    }
                }
                else
                {
                    // 数据源为空，提示用户或进行其他操作
                    MessageBox.Show("数据源为空，请加载数据后再操作。");
                }
            }
            catch (Exception)
            {

            }

        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <returns></returns>
        public List<string> GetListContent()
        {
            List<string> content = new List<string>();
            if (/*!string.IsNullOrEmpty(textBox_address.Text) &&*/ !string.IsNullOrEmpty(textBoxType.Text) && !string.IsNullOrEmpty(textBoxScale.Text))
            {

                content.Add(uiComboDataGridView2.Text);
                content.Add(textBoxType.Text);
                content.Add(textBoxScale.Text);
            }
            return content;
        }


        public void InitialData(ModelSaveString modelSaveString)
        {
            ChannelSeting channelSeting = SystemSetting.Channels[I];
            ComboBox comboBox_Type = (ComboBox)base.Controls.Find(string.Format("comboBoxCH_{0}Type", I), true)[0];
            ComboBox comboBox_ratio = (ComboBox)base.Controls.Find(string.Format("comboBoxCH_{0}ratio", I), true)[0];
            TextBox comboBoxadd = (TextBox)base.Controls.Find(string.Format("textBoxCH{0}Address", I), true)[0];
            TextBox comboBoxoffset = (TextBox)base.Controls.Find(string.Format("textBoxCH{0}Offset", I), true)[0];
            textBoxType.Text = modelSaveString.Type;
            textBoxScale.Text = modelSaveString.Scale;
            textBox_address.Text = modelSaveString.Address;
            uiComboDataGridView2.Text = modelSaveString.Name;
            textBox_offset.Text = modelSaveString.SignalOffset;
            if (Enum.TryParse(comboBox_ratio.Text, out ENUM_Ratio result_WaveRatio))
            {
                channelSeting.WaveRatio = result_WaveRatio;
            }
            if (Enum.TryParse(comboBox_Type.Text, out ENUM_001 result_SignalType))
            {
                channelSeting.SignalType = (ENUM_001)Enum.Parse(typeof(ENUM_001), (string)comboBox_Type.SelectedItem);
            }
            //if (double.TryParse(textBox_offset.Text, out double signalOffset))
            //{
            //    channelSeting.signalOffset = signalOffset;
            //}
            channelSeting.Address = Convert.ToInt32(modelSaveString.Address, 16);
            cuurentSelectItem = modelSaveString;
        }

        private void comboBox_type_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            if (I != 0)
                SystemSetting.Channels[I].SignalType = (ENUM_001)Enum.Parse(typeof(ENUM_001), comboBox.Text);

        }

        private void comboBox_scale_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            if (I != 0)
                SystemSetting.Channels[I].WaveRatio = (ENUM_Ratio)Enum.Parse(typeof(ENUM_Ratio), comboBox.Text);
        }

        private void textBox_offset_TextChanged(object sender, EventArgs e)
        {
            //TextBox textBox = sender as TextBox;
            //double offsetValue;

            //// 尝试将文本框的文本转换为double
            //if (!double.TryParse(textBox.Text, out offsetValue))
            //{
            //    // 如果转换失败，设置默认值为0
            //    textBox.Text = "0";
            //}
            //else
            //{
            //    if (I != 0)
            //        SystemSetting.Channels[I].signalOffset = double.Parse(textBox.Text);
            //}
        }
    }
}
